package com.huan.study.mongo;

import com.huan.study.mongo.domain.User;
import com.huan.study.mongo.repository.UserRepository;
import com.mongodb.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * spring data mongodb 的测试
 *
 * @author huan.fu
 */
@SpringBootApplication
@Slf4j
public class StudySpringDataMongoApplication implements CommandLineRunner {

	@Autowired
	private UserRepository userRepository;
	@Autowired
	private MongoTemplate mongoTemplate;

	public static void main(String[] args) {
		SpringApplication.run(StudySpringDataMongoApplication.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		this.queryAllUsers();
	}

	/**
	 * 删除用户
	 */
	private void removeUsers() {
		DBCollection collection = mongoTemplate.getCollection("mongo_users");
		WriteResult removeResult = collection.remove(BasicDBObject.parse("{new_age : 25}"));
		log.info("=======> remove : {}", removeResult);
	}

	/**
	 * 聚合操作
	 */
	private void aggregate() {
		DBCollection collection = mongoTemplate.getCollection("mongo_users");
		List<? extends DBObject> pipeline = Arrays.asList(
				BasicDBObject.parse("{$match : {new_age : {$gt : 20}}}"),
				BasicDBObject.parse("{$project : {new_age : 1}}"),
				BasicDBObject.parse("{$group : {_id : \"$new_age\",sums : {$sum : 1}}}")
		);
		Cursor cursor = collection.aggregate(pipeline, AggregationOptions.builder().outputMode(AggregationOptions.OutputMode.CURSOR).build());
		while (cursor.hasNext()) {
			DBObject obj = cursor.next();
			System.out.println(obj);
		}
	}

	private void findByPage() {
		Page<User> page = userRepository.findAll(new PageRequest(1, 2, Sort.Direction.DESC, "new_age"));
		System.out.println("总记录数:" + page.getTotalElements());
		System.out.println("总页数: " + page.getTotalPages());
		System.out.println("查询出来的记录数");
		for (User user : page.getContent()) {
			System.out.println(user);
		}
		System.out.println("=========================");


		DBObject query = new BasicDBObject();
		DBCollection collection = mongoTemplate.getCollection("mongo_users");
		DBCursor cursor = collection.find(query);
		cursor.skip(1).limit(2);

		while (cursor.hasNext()) {
			System.out.println(cursor.next());
		}
	}

	/**
	 * 查询方法
	 */
	private void mongodbTemplateQuery() {
		User user = User.builder()
				.age(25)
				.createTime(new Date())
				.hobbies(Arrays.asList("xx", "yy"))
				.parent(User.builder().age(26).build())
				.build();

		mongoTemplate.insert(user);

		/**
		 * 查询条件
		 */
		String queryCondition = "{new_age : { $eq : 25}}";
		/**
		 * 投影，只返回需要的字段
		 */
		String projects = "{userId : 1,new_age : 1}";
		BasicQuery query = new BasicQuery(queryCondition, projects);
		List<User> users = mongoTemplate.find(query, User.class);
		System.out.println(users);
	}

	/**
	 * 根据条件查询
	 */
	private void findByCondition() {
		userRepository.findByAgeEquals(25).forEach(System.out::println);
	}

	/**
	 * 批量添加
	 */
	private void batchInsert() {
		userRepository.insert(
				Arrays.asList(
						User.builder().age(25).createTime(new Date()).build(),
						User.builder().age(26).createTime(new Date()).build()
				)
		);
	}

	/**
	 * 替换一个用户
	 */
	private void replaceOne() {
		User oldUser = userRepository.findOne("5ad44facc9c44f0ee005aa40");
		System.out.println(oldUser);

		User newUser = User.builder()
				.userId("5ad44facc9c44f0ee005aa40")
				.age(25)
				.build();
		userRepository.save(newUser);
	}

	/**
	 * 查询所有的用户信息
	 */
	private void queryAllUsers() {
		// 查询所有的用户
		List<User> users = userRepository.findAll();
		users.forEach(System.out::println);
	}

	/**
	 * 保存一个用户
	 */
	private void saveOneUser() {
		// 保存一个用户
		userRepository.save(
				User.builder()
						.age(20)
						.createTime(new Date())
						.hobbies(Arrays.asList("学习", "java"))
						.build()
		);
	}
}
